import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, Alert, Spin, Layout } from 'antd';
import { UserOutlined, LockOutlined, WechatOutlined } from '@ant-design/icons';
import { useNavigate, Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

const { Title } = Typography;
const { Content } = Layout;

const Login = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const { login, isAuthenticated } = useAuth();
  const navigate = useNavigate();

  // 如果已经认证，重定向到主页
  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }

  const onFinish = async (values) => {
    setLoading(true);
    setError('');

    try {
      const success = await login(values.username, values.password);
      if (success) {
        navigate('/dashboard');
      } else {
        setError('登录失败，请检查用户名和密码');
      }
    } catch (err) {
      setError(err.response?.data?.message || '登录失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Card className="login-card">
        <div className="login-logo">
          <WechatOutlined style={{ fontSize: 48, color: '#1890ff' }} />
          <Title level={2} style={{ marginTop: 16, marginBottom: 0 }}>WhatsApp中间平台</Title>
          <Title level={4} style={{ margin: 0, color: '#666', fontWeight: 'normal' }}>企业级消息管理系统</Title>
        </div>

        {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 24 }} />}

        <Spin spinning={loading}>
          <Form
            name="login"
            onFinish={onFinish}
            autoComplete="off"
            layout="vertical"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                size="large" 
                block
                style={{ height: 48 }}
              >
                登录系统
              </Button>
            </Form.Item>
            
            <div style={{ textAlign: 'center', color: '#999', fontSize: 12, marginTop: 24 }}>
              使用企业账号登录 · 助力团队高效协作
            </div>
          </Form>
        </Spin>
      </Card>
    </div>
  );
};

export default Login; 